#include "Game.h"

IGame* createGame( HINSTANCE hInst, HWND hWnd )
{
	return new Game( hInst, hWnd );
}

Game::Game( HINSTANCE hInst, HWND hWnd )
{
	// initialize input devices
	m_input = new SInput2( hInst, hWnd );

	// initialize mouse coordinates
	m_mouseCoord = float3(0,0,0);

	// initialize camera
	m_camera.hand = Camera::RIGHTHANDED;

	m_camera.eye = float3( 0, 0, 20.f );
	m_camera.at  = float3( 0, 0, 0 );
	m_camera.up  = float3( 0, 1, 0 );

	m_camera.projectionType = Camera::PERSPECTIVE_FOV;
	m_camera.perspectiveFov.fovy = D3DXToRadian(45.f);
	m_camera.perspectiveFov.aspect = 1024.f/768.f;

	m_camera.zn = 1.0f;
	m_camera.zf = 100.0f;

	// initialize polygon
	m_polygon.push_back( float3( -0.5, -0.5, 0 ) );
	m_polygon.push_back( float3( 0.5, -0.5, 0 ) );
	m_polygon.push_back( float3( 0, 0.5, 0 ) );
}

Game::~Game()
{
	m_polygonView.destroy();
	m_d3dDevice = 0;
	delete m_input;
}

void Game::onCreateGraphics( D3DDevice device )
{
	m_d3dDevice = device;
	m_polygonView.initialize( m_d3dDevice );
	m_polygonView.setup( m_polygon, float4( 1.0f, 1.0f, 1.0f, 1.0f ) );

	m_d3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CW );

	float44 world = identity44();
	float44 view = m_camera.view();
	float44 proj = m_camera.projection();

	m_d3dDevice->SetTransform( D3DTS_WORLD, &world );
	m_d3dDevice->SetTransform( D3DTS_VIEW, &view );
	m_d3dDevice->SetTransform( D3DTS_PROJECTION, &proj );
}

void Game::onResetGraphics( D3DDevice device )
{
	//TODO: Add code to handle lost device ( resizing issue )

	m_d3dDevice = device;

	m_polygonView.destroy();
	m_polygonView.initialize( m_d3dDevice );
	m_polygonView.setup( m_polygon, float4( 1.0f, 1.0f, 1.0f, 1.0f ) );

	m_d3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CW );

	float44 view = m_camera.view();
	float44 proj = m_camera.projection();

	m_d3dDevice->SetTransform( D3DTS_VIEW, &view );
	m_d3dDevice->SetTransform( D3DTS_PROJECTION, &proj );
}

void Game::onLostGraphics()
{
}

void Game::onFrameMove(float dt)
{
	SInput2::MOUSESTATE mouseState = m_input->mouseState();

	m_mouseCoord[0] += mouseState.x/32.f;
	m_mouseCoord[1] -= mouseState.y/32.f;
}

void Game::onFrameRender(float dt)
{
	float44 world = translation( m_mouseCoord );
	m_polygonView.render( world );
}

void Game::onDestroyGraphics()
{
}
